const express = require('express');
const cors = require('cors');
const path = require('path');
const { createServer } = require('http');
const { Server } = require('socket.io');
require('dotenv').config();

// 创建Express应用
const app = express();
const server = createServer(app);
const PORT = process.env.PORT || 3000;

// 创建Socket.io服务器
const io = new Server(server, {
  cors: {
    origin: "*", // 在生产环境中应该设置具体的域名
    methods: ["GET", "POST"]
  }
});

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 请求日志中间件
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`);
  next();
});

// 操作日志中间件
const operationLog = require('./middleware/operationLog');
app.use(operationLog);

// 健康检查接口
app.get('/health', (req, res) => {
  console.log('健康检查请求');
  res.json({
    code: 200,
    message: '服务运行正常',
    timestamp: new Date().toISOString(),
    uptime: process.uptime()
  });
});

// 数据库配置
const db = require('./config/db');

// 认证中间件
const { authenticateToken } = require('./middleware/auth');

// Socket.io连接处理
io.on('connection', (socket) => {
  console.log('用户连接:', socket.id);
  
  // 用户认证
  socket.on('authenticate', (token) => {
    // 这里应该验证token并关联用户ID到socket
    // 简化处理，实际项目中需要验证JWT token
    socket.userId = token; // 简化处理，实际应该解析token获取用户信息
    console.log('用户认证:', token);
  });
  
  // 断开连接
  socket.on('disconnect', () => {
    console.log('用户断开连接:', socket.id);
  });
});

// 路由
app.use('/api', require('./routes/auth'));
app.use('/api', authenticateToken, require('./routes/logs'));
app.use('/api', authenticateToken, require('./routes/users'));
app.use('/api', authenticateToken, require('./routes/dashboard'));
app.use('/api', authenticateToken, require('./routes/files'));
app.use('/api', authenticateToken, require('./routes/messages'));
app.use('/api', authenticateToken, require('./routes/workflow'));
app.use('/api', authenticateToken, require('./routes/ai'));

// 静态文件服务
app.use('/uploads', express.static(path.join(__dirname, '../uploads')));

// 404处理
app.use((req, res) => {
  console.log(`404 - 未找到路由: ${req.originalUrl}`);
  res.status(404).json({
    code: 404,
    message: '接口不存在'
  });
});

// 全局错误处理中间件（必须放在路由之后）
app.use(require('./middleware/errorHandler'));

// 启动服务器
server.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
  console.log(`Health check: http://localhost:${PORT}/health`);
  console.log(`Socket.io server is running`);
});

// 导出io对象，供其他模块使用
module.exports = { io };